package org.seedltd.upms.task;

import java.util.List;

import org.seedltd.core.base.BasePage;
import org.seedltd.upms.model.detection.entity.DetectionTerminal;
import org.seedltd.upms.model.detection.vo.CommodityInfo;
import org.seedltd.upms.service.detection.DetectionTerminalPipelineService;
import org.seedltd.upms.service.detection.DetectionTerminalService;
import org.seedltd.upms.service.detection.VendingMachineApiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ScheduledTasks {

    @Value("${spring.profiles.active:dev}")
    private String profiles;

    private final VendingMachineApiService vendingMachineApiService;
    private final DetectionTerminalService detectionTerminalService;
    private final DetectionTerminalPipelineService detectionTerminalPipelineService;

    public ScheduledTasks(VendingMachineApiService vendingMachineApiService, DetectionTerminalService detectionTerminalService,
                          DetectionTerminalPipelineService detectionTerminalPipelineService) {
        this.vendingMachineApiService = vendingMachineApiService;
        this.detectionTerminalService = detectionTerminalService;
        this.detectionTerminalPipelineService = detectionTerminalPipelineService;
    }

    private boolean isDev() {
        return "dev".equals(profiles);
    }

    /**
     * 每天凌晨3点执行一次登入获取token
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void login() {
        if (!isDev()) {
            vendingMachineApiService.login();
        }
    }

    private int start = 0;

    /**
     * 每5分钟更新一次货道的数据
     */
    @Scheduled(cron = "0 */5 * * * *")
    public void updatePipeline() {
        if (isDev()) {
            return;
        }
        int size = 20;
        BasePage<DetectionTerminal> basePage = new BasePage<>(start, size);
        List<DetectionTerminal> detectionTerminals = detectionTerminalService.listVm(basePage);
        if (CollectionUtils.isEmpty(detectionTerminals)) {
            start = 0;
        } else {
            for (DetectionTerminal detectionTerminal : detectionTerminals) {
                List<CommodityInfo> commoditys = vendingMachineApiService.queryCommodity(detectionTerminal.getMachineId());
                detectionTerminalPipelineService.update(commoditys, detectionTerminal.getId());
            }
            if (detectionTerminals.size() < size) {
                start = 0;
            }
            start++;
        }
    }
}
